package com.talos.ums.service.childuser;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.childuser.vo.UmsChildUserPageReqVO;
import com.talos.ums.controller.admin.childuser.vo.UmsChildUserSaveReqVO;
import com.talos.ums.dal.dataobject.childuser.UmsChildUserDO;
import com.talos.ums.dal.mysql.childuser.UmsChildUserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 子账号添加记录表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsChildUserServiceImpl implements UmsChildUserService {

    @Resource
    private UmsChildUserMapper childUserMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createChildUser(UmsChildUserSaveReqVO createReqVO) {
        // 插入
        UmsChildUserDO childUser = BeanUtils.toBean(createReqVO, UmsChildUserDO.class);
        childUserMapper.insert(childUser);
        // 返回
        return childUser.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChildUser(UmsChildUserSaveReqVO updateReqVO) {
        // 校验存在
        validateChildUserExists(updateReqVO.getId());
        // 更新
        UmsChildUserDO updateObj = BeanUtils.toBean(updateReqVO, UmsChildUserDO.class);
        childUserMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChildUser(Long id) {
        // 校验存在
        validateChildUserExists(id);
        // 删除
        childUserMapper.deleteById(id);
    }

    private void validateChildUserExists(Long id) {
        if (childUserMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsChildUserDO getChildUser(Long id) {
        return childUserMapper.selectById(id);
    }

    @Override
    public PageResult<UmsChildUserDO> getChildUserPage(UmsChildUserPageReqVO pageReqVO) {
        return childUserMapper.selectPage(pageReqVO);
    }

}
